package tests;

import common.IP;
import common.Utils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.time.Duration;

public class SignUp extends Utils{

    public static String url = "http://" + IP.ip + "/login.html";

    public SignUp() {
        super(url);
    }

    //封装弹窗方法
    public void waitAlert(WebDriver driver){
        //显式等待弹窗的出现
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        Alert alert =null;
        try {
            //检测弹窗的存在，存在会显式返回一个有效的alert对象
            alert = wait.until(ExpectedConditions.alertIsPresent());
            alert.accept();
        }catch (Exception e){
            System.out.println("SignUpFail");
        }
    }

    //注册失败
    public void fail() throws InterruptedException, IOException {
        //刷新一下
        driver.navigate().refresh();
        //1.账号和密码都不输入
        driver.findElement(By.cssSelector("#register-btn")).click();
        //弹窗确认
        waitAlert(driver);

        //2.输入用户名不输入密码
        String username = Utils.generateRandomUsername();
        driver.findElement(By.cssSelector("#username")).sendKeys(username);
        driver.findElement(By.cssSelector("#register-btn")).click();
        waitAlert(driver);


        //通过刷新清空输入框
        driver.navigate().refresh();
        //3.输入密码不输入用户名
        String password = Utils.generateRandomPassword();
        driver.findElement(By.cssSelector("#password")).sendKeys(password);
        driver.findElement(By.cssSelector("#register-btn")).click();
        waitAlert(driver);

        //通过刷新清空输入框
        driver.navigate().refresh();
        //4.输入的用户名和密码并且用户名已经存在
        driver.findElement(By.cssSelector("#username")).sendKeys("zhangsan");
        driver.findElement(By.cssSelector("#password")).sendKeys("123");
        driver.findElement(By.cssSelector("#register-btn")).click();
        waitAlert(driver);
    }



    /**
     * 注册成功
     */
    public void success() {
        driver.navigate().refresh();

        //生成随机的用户名和密码
        String username = Utils.generateRandomUsername();
        String password = Utils.generateRandomPassword();
        //找到用户名输入框并输入
        driver.findElement(By.cssSelector("#username")).sendKeys(username);
        //找到密码输入框并输入
        driver.findElement(By.cssSelector("#password")).sendKeys(password);
        //点击注册按钮
        driver.findElement(By.cssSelector("#register-btn")).click();
        //点击注册后 会出现弹窗 弹窗确认
        waitAlert(driver);
        //弹窗确认后会跳转到登录页面 检查页面元素是否存在
        driver.findElement(By.cssSelector("body > div.login-container > div > h3"));
        //获取页面标题
        String title= driver.getTitle();
        //字符串断言
        assert title.equals("登录");
        System.out.println(title);
    }

}
